﻿
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace EnterpriseWeChatInform
{
    /// <summary>
    /// 企业微信消息类型
    /// </summary>
    public enum WeChatMessageType
    {
        Markdown,
        Text,
        Image,
        TextWithMention
    }

    /// <summary>
    /// 消息内容封装
    /// </summary>
    public record WeChatMessage(
        WeChatMessageType MessageType,
        string Content,
        string? Base64 = null,
        string? Md5 = null,
        List<string>? Mentions = null
    );

    /// <summary>
    /// 企业微信通知核心服务
    /// </summary>
    public sealed class WeChatNotifier : IDisposable
    {
        private readonly HttpClient _httpClient;
        private readonly string _webhookUrl;
        private readonly string _botName;

        public WeChatNotifier(string webhookUrl, string botName)
        {
            _httpClient = new HttpClient();
            _webhookUrl = webhookUrl ?? throw new ArgumentNullException(nameof(webhookUrl));
            _botName = botName ?? throw new ArgumentNullException(nameof(botName));
        }

        /// <summary>
        /// 通用消息发送方法
        /// </summary>
        public async Task<Tuple<bool, string>> SendAsync(WeChatMessage message)
        {
            try
            {
                var payload = CreatePayload(message);
                var json = JsonSerializer.Serialize(payload, new JsonSerializerOptions
                {
                    DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
                });

                var response = await _httpClient.PostAsync(
                    _webhookUrl,
                    new StringContent(json, Encoding.UTF8, "application/json")
                );

                return response.IsSuccessStatusCode
                    ? Tuple.Create(true, "消息发送成功")
                    : Tuple.Create(false, $"HTTP 错误: {response.StatusCode}");
            }
            catch (Exception ex)
            {
                return Tuple.Create(false, $"发送失败: {ex.Message}");
            }
        }

        private object CreatePayload(WeChatMessage message)
        {
            return message.MessageType switch
            {
                WeChatMessageType.Markdown => new
                {
                    msgtype = "markdown",
                    markdown = new { content = FormatMarkdown(message.Content) }
                },

                WeChatMessageType.Text => new
                {
                    msgtype = "text",
                    text = new { content = message.Content }
                },

                WeChatMessageType.Image => new
                {
                    msgtype = "image",
                    image = new { base64 = message.Base64, md5 = message.Md5 }
                },

                WeChatMessageType.TextWithMention => new
                {
                    msgtype = "text",
                    text = new
                    {
                        content = message.Content,
                        mentioned_mobile_list = message.Mentions ?? new List<string>()
                    }
                },

                _ => throw new NotSupportedException("不支持的消息类型")
            };
        }

        private string FormatMarkdown(string content)
        {
            return $"# <font color=\"warning\">{_botName}通知</font>\n{content}";
        }

        public void Dispose()
        {
            _httpClient.Dispose();
            GC.SuppressFinalize(this);
        }
    }
}
